package top.igotcha.chapter.chapter7.ScheduledThreadPoolExecutor01;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gotcha
 * @date 2021/3/15
 * @describe ScheduledThreadPool延时执行
 */
@Slf4j(topic = "ScheduledThreadPoolExecutorTest01")
public class ScheduledThreadPoolExecutorTest01 {
    public static void main(String[] args) {
        // 自定义线程工厂
        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger atomicInteger = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "gotchaThread_" + atomicInteger.getAndIncrement());
            }
        };

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2,factory);
        pool.schedule(()->
            {
                log.debug("Task1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },1, TimeUnit.SECONDS);
        pool.schedule(()-> log.debug("Task2"),1, TimeUnit.SECONDS);
    }
}
